﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using MiniStock.Entities.Common.Events;

namespace MiniStock.BusinessLogic.EventDispatcher.MessageMap
{
    public static class MessageMapExtender
    {
        private static DataContractSerializer _serializer = null;

        public static void InitSerializer()
        {
            _serializer = new DataContractSerializer(typeof(MessageMap));
        }

        public static MessageMap ToMessageMap(this string contentXml)
        {
            if (contentXml == null)
                return null;

            if (_serializer == null)
                InitSerializer();
            //throw new InvalidOperationException("Serializer must be initialized");

            using (var ms = new MemoryStream())
            {
                var sw = new StreamWriter(ms);
                sw.Write(contentXml);
                sw.Flush();

                ms.Seek(0, SeekOrigin.Begin);

                return _serializer.ReadObject(ms) as MessageMap;
            }
        }

        public static string ToXmlString(this MessageMap item)
        {
            if (item == null)
                return null;

            if (_serializer == null)
                InitSerializer();
            //throw new InvalidOperationException("Serializer must be initialized");

            string result = null;
            using (var ms = new MemoryStream())
            {
                _serializer.WriteObject(ms, item);
                ms.Seek(0, SeekOrigin.Begin);
                using (var sr = new StreamReader(ms))
                {
                    result = sr.ReadToEnd();
                }
            }

            return result;
        }
    }
}
